TWB.New_Module({
	///////////////////////////
	name : "FarmTool",		 //
	author : "enduo",        //
	version : 1.0,           //
	///////////////////////////
	
	settings : {
		farmtsize : {
			type : "text"
		},
		ft_tutorial : {
			type : "checkbox"
		}
	},
	FARMS : {},
	Add_Temp : function(units){
		if(typeof TWB.Modules.FarmTool.TEMP!="undefined"){
			TWB.Modules.FarmTool.TEMP[1].units=units;
			TWB.Modules.FarmTool.FARMS=TWB.get_var("farms_"+TWB.language+"_"+TWB.World(),{});
			if(typeof TWB.Modules.FarmTool.FARMS[TWB.Modules.FarmTool.TEMP[0]]=="undefined"){
				TWB.Modules.FarmTool.FARMS[TWB.Modules.FarmTool.TEMP[0]]=[];
			}
			TWB.Modules.FarmTool.FARMS[TWB.Modules.FarmTool.TEMP[0]].push(TWB.Modules.FarmTool.TEMP[1]);
			delete TWB.Modules.FarmTool.TEMP;
			// Save
			TWB.set_var("farms_"+TWB.language+"_"+TWB.World(),TWB.Modules.FarmTool.FARMS);
			if(TWB.get_var("ft_tutorial")){
				TWB.Notify(TWB.lang("farmadded"),"TWB-FarmTool");
			}
		}
	},
	Add_Single : function(id){
		if(!TWB.logged()){
			return alert(TWB.lang("notlogged"));
		}
		if(TWB.Modules.Icons.Screen()=="info_village"){
			try{
				var fid=TWB.Xpath("//*[contains(@href,'&target=')]",9).href.match(/target=(\d+)/)[1];
			}catch(e){
				return;
			}
			var target=TWB.Xpath("//*[@id='content_value']//table//table//tr[2]/td[2]",9).innerHTML.match(/\d+\|\d+/)[0];
			if(typeof id=="undefined"){
				TWB.Modules.Villages.Action="Modules.FarmTool.Add_Single";
				if(TWB.get_var("ft_tutorial")){
					TWB.Notify(TWB.lang("selector"),"TWB-FarmTool");
				}
			}
			else{
				if(typeof TWB.Modules.FarmTool.FARMS[id]=="undefined"){
					TWB.Modules.FarmTool.FARMS[id]=[];
				}
				
				var i;
				var flag=false;
				for(i=0; i<TWB.Modules.FarmTool.FARMS[id].length; i++){
					if(TWB.Modules.FarmTool.FARMS[id][i].coords==target){
						flag=true;
						break;
					}
				}
				
				if(!flag){
					TWB.Modules.FarmTool.TEMP=[id,{
						id : fid,
						coords : target,
						units : "",
						label : ""
					}];
					TWB.Modules.Units.Action="Modules.FarmTool.Add_Temp";
					TWB.Modules.Units.Show();
					if(TWB.get_var("ft_tutorial")){
						TWB.Notify(TWB.lang("addunits"),"TWB-FarmTool");
					}
				}
				else{
					alert(TWB.lang("farmalready"));
				}
			}
		}
		else{
			alert(TWB.lang("infovil"));
		}
	},
	Add_Reports : function(){
		if(!TWB.logged()){
			return alert(TWB.lang("notlogged"));
		}
		if(TWB.Modules.Icons.Screen()=="report" && TWB.Modules.Icons.Mode()=="all" && TWB.URL().match(/view=/)!=null){
			var target=TWB.Xpath("//*[@id='attack_info_def']//a[contains(@href,'info_village')]",9);
			var fid=target.href.match(/id=(\d+)/)[1];
			target=target.innerHTML.match(/\d+\|\d+/)[0];
			var id=TWB.Xpath("//*[@id='attack_info_att']//a[contains(@href,'info_village')]",9).href.match(/id=(\d+)/)[1];
			
			if(typeof TWB.Modules.FarmTool.FARMS[id]=="undefined"){
				TWB.Modules.FarmTool.FARMS[id]=[];
			}
			
			var i;
			var flag=false;
			for(i=0; i<TWB.Modules.FarmTool.FARMS[id].length; i++){
				if(TWB.Modules.FarmTool.FARMS[id][i].coords==target){
					flag=true;
					break;
				}
			}
			
			if(!flag){
				var units="";
				TWB.Modules.FarmTool.TEMP=[id,{
					id : fid,
					coords : target,
					units : "",
					label : ""
				}];
				TWB.Modules.Units.Action="Modules.FarmTool.Add_Temp";
				TWB.Modules.Units.Show();
				if(TWB.get_var("ft_tutorial")){
					TWB.Notify(TWB.lang("addunits"),"TWB-FarmTool");
				}
			}
			else{
				alert(TWB.lang("farmalready"));
			}
		}
		else{
			alert(TWB.lang("gotoreport"));
		}
	},
	Add_Coords : function(id){
		if(!TWB.logged()){
			return alert(TWB.lang("notlogged"));
		}
		
		if(typeof TWB.Modules.FarmTool.tmp_farms=="undefined"){
			var farms=prompt(TWB.lang("addtargets"));
			if(farms){
				if(farms.match(/\d+\|\d+/)){
					TWB.Modules.FarmTool.tmp_farms=farms.match(/\d+\|\d+/g);
				}
				else{
					return alert(TWB.lang("invinput"));
				}
			}
		}
		if(typeof id=="undefined" && typeof flag=="undefined"){
			TWB.Modules.Villages.Action="Modules.FarmTool.Add_Coords";
			if(TWB.get_var("ft_tutorial")){
				TWB.Notify(TWB.lang("selector"),"TWB-FarmTool");
			}
		}
		else{
			TWB.Modules.FarmTool.FARMS=TWB.get_var("farms_"+TWB.language+"_"+TWB.World(),{});
			TWB.Modules.FarmTool.tmp_id=id;
			TWB.Modules.Units.Action="Modules.FarmTool.Add_Coords_";
			TWB.Modules.Units.Show();
			if(TWB.get_var("ft_tutorial")){
				TWB.Notify(TWB.lang("addunits"),"TWB-FarmTool");
			}
		}
	},
	Add_Coords_ : function(units){
		TWB.Modules.FarmTool.tmp_units=units;
		TWB.Processor.start("farm_coords","Modules.FarmTool.Add_Coords_Loop","*",false);
		TWB.Modules.Icons.GoTo("place","command");
	},
	Add_Coords_Loop : function(){
		if(TWB.URL().match("try=confirm")){
			// Get Id of Farm and add then trim and go to Command
			var i;
			var nomatch=true;
			if(typeof TWB.Modules.FarmTool.FARMS[TWB.Modules.FarmTool.tmp_id]!="undefined"){
				for(i=0; i<TWB.Modules.FarmTool.FARMS[TWB.Modules.FarmTool.tmp_id].length; i++){
					if(TWB.Modules.FarmTool.FARMS[TWB.Modules.FarmTool.tmp_id][i].coords==TWB.Modules.FarmTool.tmp_farms[0]){
						nomatch=false;
						break;
					}
				}
			}
			else{
				TWB.Modules.FarmTool.FARMS[TWB.Modules.FarmTool.tmp_id]=[];
			}
			if(typeof TWB.Modules.FarmTool.FARMS[TWB.Modules.FarmTool.tmp_id]=="undefined" || nomatch){
				TWB.Modules.FarmTool.FARMS[TWB.Modules.FarmTool.tmp_id].push({
					id : TWB.Xpath("//*[contains(@href,'screen=info_village')]",9).href.match(/id=(\d+)/)[1],
					coords : TWB.Modules.FarmTool.tmp_farms[0],
					units : TWB.Modules.FarmTool.tmp_units,
					label : ""
				});
				// Save
				TWB.set_var("farms_"+TWB.language+"_"+TWB.World(),TWB.Modules.FarmTool.FARMS);
			}
			// Trim
			TWB.Modules.FarmTool.tmp_farms.splice(0,1);
			TWB.Modules.Icons.GoTo("place","command");
		}
		else{
			target=TWB.Modules.FarmTool.tmp_farms[0];
			if(typeof target=="undefined"){
				TWB.Modules.FarmTool.Add_Coords_Finish();
			}
			else{
				TWB.Xpath("//*[@name='x']",9).value=target.split("|")[0];
				TWB.Xpath("//*[@name='y']",9).value=target.split("|")[1];
				WD=content;
				if(typeof WD.wrappedJSObject!="undefined"){
					WD=WD.wrappedJSObject;
				}
				WD.selectAllUnits(true);
				TWB.Xpath("//*[@type='submit']",9).click();
			}
		}
	},
	Add_Coords_Finish : function(){
		delete tmp_id;
		delete tmp_units;
		delete tmp_farms;
		TWB.Processor.stop("farm_coords");
		if(TWB.get_var("ft_tutorial")){
			TWB.Notify(TWB.lang("farmadded"),"TWB-FarmTool");
		}
	},
	Show : function(){
		window.openDialog("chrome://twbooster/content/farm_tool.xul", "","chrome,dialog,resizable=yes", TWB.lang("label_farmtool"), window);
	},
	Launch : function(){
		var params={
			out : []
		};
		window.openDialog("chrome://twbooster/content/farm_tool.xul", "","modal,chrome,dialog,resizable=yes", TWB.lang("label_farmtool"), window, params);
		if(params.out.length>0){
			TWB.Modules.Bots.enable_autoskip=false;
			TWB.Modules.FarmTool.farming=params.out;
			TWB.Processor.start("farming","Modules.FarmTool.Sender","*",false);
			TWB.Load_Url(TWB.Modules.Icons.GoTo("place","command",true)+"&village="+params.out[0][0]+"&target="+params.out[0][1]+"&extra");
		}
	},
	Sender : function(){
		if(TWB.Modules.Icons.Screen()=="place"){
			if(TWB.URL().match("try=confirm")){
				TWB.Modules.FarmTool.farming.splice(0,1);
				// Submit
				TWB.Xpath("//input[@type='submit']",9).click();
			}
			else{
				if(TWB.URL().match("&extra")){
					// Set units
					var ounit;
					var flag=false;
					var units=TWB.Modules.Units.String2Obj(TWB.Modules.FarmTool.farming[0][2]);
					for(ounit in units){
						var item=TWB.Xpath("//input[@name='"+ounit+"']",9);
						if(item!=null && units[ounit]>0 && units[ounit]-item.nextSibling.nextSibling.innerHTML.match(/\d+/)[0]<=0){
							flag=true; // At least one has been sent
							item.value=units[ounit];
						}
					}
					if(flag){
						// Submit
						TWB.Xpath("//input[@type='submit']",9).click();
					}
					else{
						TWB.Modules.FarmTool.farming.splice(0,1);
						TWB.Modules.FarmTool.SenderNext();
					}
				}
				else{
					TWB.Modules.FarmTool.SenderNext();
				}
			}
		}
	},
	SenderNext : function(){
		// Back from submit, continue or die
		if(TWB.Modules.FarmTool.farming.length>0){
			TWB.Load_Url(TWB.Modules.Icons.GoTo("place","command",true)+"&village="+TWB.Modules.FarmTool.farming[0][0]+"&target="+TWB.Modules.FarmTool.farming[0][1]+"&extra");
		}
		else{
			TWB.Modules.Bots.enable_autoskip=true;
			delete TWB.Modules.FarmTool.farming;
			TWB.Processor.stop("farming");
		}
	},
	Find_Farms : function(){
		if(!TWB.logged()){
			return alert(TWB.lang("notlogged"));
		}
		
		var E=TWB.gei("TWB-FarmTool-FindFarms");
		if(E.style.color=="blue"){
			return;
		}
		E.style.color="blue";
		
		var RAD=prompt(TWB.lang("ffradius"),10);
		if(!RAD){
			return;
		}
		
		var xy=TWB.Xpath("//*[@id='menu_row2']//td[@class='box-item']",9).textContent.match(/\d+\|\d+/g)[0];
		var params="world="+TWB.World()+"&barab=1&minptsb=26&maxptsb=12000&script=1&idia=0&dia="+RAD+"&coordinate="+xy+"&minpts=26&maxpts=12000&submit=Find Farms!";
		TWB.$.ajax({
			url: "http://"+TWB.World(true)+".twmentor.com/?tool=finder",
			type : "POST",
			data : params,
			async : true,
			success: function(response){
				try{
					var farms=response.split("<fieldset>")[1].split("</fieldset")[0].match(/\d+\|\d+/g);
					if(farms!=null && farms.length>0){
						var x=prompt(TWB.lang("foundfarms",[farms.length]));
						if(x && x>0){
							x=Math.min(x,farms.length);
							TWB.Modules.FarmTool.tmp_farms=farms.splice(0,x);
							TWB.Modules.FarmTool.Add_Coords();
						}
					}
					else{
						alert(TWB.lang("nofarms"));
					}
					var E=TWB.gei("TWB-FarmTool-FindFarms");
					E.style.color="black";
				}catch(e){
					TWB.log(e,"Find Farms");
					var E=TWB.gei("TWB-FarmTool-FindFarms");
					E.style.color="black";
				}
			}
		});
	},
	Import : function(){
		if(!TWB.logged()){
			return alert(TWB.lang("notlogged"));
		}
		// Reload
		var nsIFilePicker=TWB.Ci.nsIFilePicker;
		var fp=TWB.Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
		fp.appendFilter(TWB.lang("tffile"),"*.twb.csv");
		fp.init(window,TWB.lang("importchoosefile"),nsIFilePicker.modeOpen);
		if(!fp.show()){
			var path=fp.file.path;
			var fo=TWB.Cc["@mozilla.org/file/local;1"].createInstance(TWB.Ci.nsILocalFile);
			fo.initWithPath(path);
			var ist = TWB.Cc["@mozilla.org/network/file-input-stream;1"].createInstance(TWB.Ci.nsIFileInputStream);
			ist.init(fo,0x01,00004,null);
			var szt = TWB.Cc["@mozilla.org/scriptableinputstream;1"].createInstance(TWB.Ci.nsIScriptableInputStream);
			szt.init(ist);
			var data = szt.read(szt.available());
			szt.close();
			data=data.split("\n");
			var i;
			var vid=null;
			TWB.Modules.FarmTool.FARMS={};
			for(i=3; i<data.length; i++){
				var line=data[i].split(",");
				if(line[0].length>0){
					// This would be a village
					vid=line[0].match(/\d+/)[0];
					TWB.Modules.FarmTool.FARMS[vid]=[];
				}
				else{
					// This would be its farm
					TWB.Modules.FarmTool.FARMS[vid].push({
						id : line[1].match(/\d+/)[0],
						coords : line[2],
						label : line[3],
						units : line[4]
					});
				}
			}
			TWB.set_var("farms_"+TWB.language+"_"+TWB.World(),TWB.Modules.FarmTool.FARMS);
			TWB.Modules.FarmTool.Show();
		}
	},
	Export : function(){
		if(!TWB.logged()){
			return alert(TWB.lang("notlogged"));
		}
		// Reload
		TWB.Modules.FarmTool.FARMS=TWB.get_var("farms_"+TWB.language+"_"+TWB.World(),{});
		var nsIFilePicker=TWB.Ci.nsIFilePicker;
		var fp=TWB.Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
		fp.appendFilter(TWB.lang("tffile"),"*.twb.csv");
		fp.init(window,TWB.lang("exportchoosefile"),nsIFilePicker.modeSave);
		if(!fp.show()){
			var i;
			var vid;
			var data="Village Id,Name\n,Farm Id,Coords,Label,Units\n\n";
			var path=fp.file.path+".twb.csv";
			for(vid in TWB.Modules.FarmTool.FARMS){
				if(!TWB.gei("TWB-v"+vid)){
					continue;
				}
				// Village Level
				data+="{"+vid+"},"+TWB.gei("TWB-v"+vid).getAttribute("value")+"\n";
				// Farm Level
				for(i=0; i<TWB.Modules.FarmTool.FARMS[vid].length; i++){
					data+=",{"+TWB.Modules.FarmTool.FARMS[vid][i].id+"},"+TWB.Modules.FarmTool.FARMS[vid][i].coords+","+TWB.Modules.FarmTool.FARMS[vid][i].label+","+TWB.Modules.FarmTool.FARMS[vid][i].units;
					if(i<TWB.Modules.FarmTool.FARMS[vid].length-1){
						data+="\n";
					}
				}
			}
			var fo=TWB.Cc["@mozilla.org/file/local;1"].createInstance(TWB.Ci.nsILocalFile);
			fo.initWithPath(path);
			if(fo.exists()){
				// Overwrite
				fo.remove(true);
			}
			fo.create(0,0x0600);
			var ostream = TWB.Cc["@mozilla.org/network/file-output-stream;1"].createInstance(TWB.Ci.nsIFileOutputStream);
			ostream.init(fo, 0x02 | 0x08 | 0x20, 0666, ostream.DEFER_OPEN); 
			var converter = TWB.Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(TWB.Ci.nsIScriptableUnicodeConverter);
			converter.charset = "UTF-8";
			var istream = converter.convertToInputStream(data);
			Components.utils.import("resource://gre/modules/NetUtil.jsm");
			NetUtil.asyncCopy(istream, ostream);
		}
	},
});
